<?php
declare (strict_types = 1);

namespace app\controller\adminapi\v1\setting;



use app\services\admin\setting\RoleServices;
//use app\dao\admin\RoleDao;

use app\BaseController;

use app\Request;


//use think\App;
//use think\facade\Config;
use think\facade\Db;
use think\facade\Cache;


use support\Container;


use Exception;



class RoleController extends BaseController
{

    /**
     * 构造方法
     * RoleServices constructor.
     */
	public function __construct()
	{
        //$this->services = new RoleServices;
        $this->services = Container::get(RoleServices::class);
	}
    


    /**
     	* 显示资源列表
     	*
     	* @return \support\Response
    */
    public function index(Request $request)
	{
        $where = $request->getParams([
            ['role_name', '', '', 'role_name_like'],
            //['delete_time', null],
            ['status', null],	//null表示使用 search搜索器的 软删除（>=-1）
        ]);
        [$page, $limit] = $request->getParams([
            ['page', 1],
            ['limit', 10],
        ], 1);
        //$where['level'] = $this->adminInfo['level'] + 1;
        //return app('json')->success($this->services->getList($where));

		
		static::validate($where, [
			'role_name_like' => 'max:32',
		], [], true, true);
		static::validate(['page' => $page, 'limit' => $limit], [
			'page' => 'between:1,999',
			'limit' => 'between:1,100',
		], [], true, true);


		/** @var RoleServices $services */
		//$services = app()->make(RoleServices::class);
		
		$ret = $this->services->getList($where, $page, $limit,
			"id, role_name, description, rules, status", ['id', 'ASC']);
			
        return ret_value(0, "", 
			$ret['list'],
			200, [], ["count" => $ret['count']]
		);
	}

	/**
	 * 保存新建的资源
	 *
	 * @param  \app\Request  $request
	 * @return \support\Response
	*/
	public function store(Request $request)
	{
        $data = $request->getParams([
            ['role_name', ''],
            ['description', ''],
            ['rules', ''],
        ]);

		
		static::validate($data, [
			'role_name' => 'require|chsDash|max:32',
			'description' => 'max:255',
			//'rules' => '',
		]);


        // $data['level'] = $this->adminInfo['level'] + 1;
		/*
        try {
			$this->services->save($data);
        }
		catch (\RuntimeException $e) {
			return ret_value(-1, $e->getMessage());
		}
		catch (\Exception $e) {
			return ret_value(-1, $e->getMessage());
		}
		*/
		
		$this->services->save($data);
        return ret_value(0, "Success");
	}

	/**
	 * 显示指定的资源
	 *
	 * @param  string  $id
	 * @return \support\Response
	*/
	public function show(Request $request, $id)
	{
		/*$t1 = \think\facade\Db::connect('local')
		->table('lms_user_info')
		->where('id', $id)
		->find();

		return json($t1);
		*/


		if(strpos($id, '_') !== false)
		{
			$ids = explode('_', $id);
			$where = [['id', 'in', $ids]];
		}
		else {
			$where = ['id' => $id];
		}
        //$where['level'] = $this->adminInfo['level'] + 1;
        //return app('json')->success($this->services->getList($where));

		/** @var UserServices $services */
		//$services = app()->make(UserServices::class);

		$ret = $this->services->selectList($where, null, null,
			"id, role_name, rules, description, level, status", ['id', 'ASC']
		)->toArray();

        return ret_value(0, "", $ret);
	}

	/**
	 * 保存更新的资源
	 *
	 * @param  \app\Request  $request
	 * @param  int  $id
	 * @return \support\Response
	*/
	public function update(Request $request, $id)
	{
        $data = $request->getParams([
            ['id', $id],
            //['account'],
            ['role_name'],
            ['rules'],
            ['description'],
            ['status'],
        ]);

		
		static::validate($data, [
			'id' => 'require|integer',
			'role_name' => 'chsDash|max:32',
			'description' => 'max:255',
			//'rules' => '',
			'status' => 'in:0,1',
		]);


		$ret = $this->services->update((int)$id, $data);
        if ($ret)
		{
			return ret_value(0, "Success");
        }
		else
		{
			return ret_value(-1, "Fail");
        }
	}

	/**
	 * 删除指定资源（$id为单个数字 或 多个用_分隔的数字）
	 * @param int|string $id
	 * @return \support\Response
	*/
	public function destroy(Request $request, $id)
	{
        $data = $request->getParams([
            ['data', $id],
		]);
		static::validate($data, [
			'data' => 'require',
		]);


		//var_dump($id);
        //$ids = is_array($id) ? $id : (is_string($id) ? explode(',', $id) : func_get_args());
		$ids = explode('_', $data['data']);
		//var_dump($request->param());
		//var_dump($ids);
        //if (!$id) return app('json')->fail('删除失败，缺少参数');
		$ret = $this->services->batchUpdate($ids, ['status' => -1, 'delete_time' => date("Y-m-d H:i:s")]);
		//var_dump($ret);
        if ($ret)
			return ret_value(0, "Success");
        else
			return ret_value(-1, "Fail");
	}
}
